<?php


namespace app\award;

// 处理复购分红
use app\models\MonthProfit;
use app\models\order\Order;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserLevel;
use app\models\ZSetting;
use app\models\ZSetting2;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class ProfitOld
{
    protected static $users = [];

    // 区分类型
    protected static $type;

    public static function getList($type = 1)
    {
        self::$type = $type;


        // 指定等级的才有分红
        $users = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip4']])
            ->select(['id'])
            ->column();


        // 子团队,
        $data = [];
        foreach ($users as $user) {
            $children = Chain::getChildrenAllOperate($user, false, ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            $manager = Chain::getChildrenAllOperate($user, true, ['id']);
            $manager = ArrayHelper::getColumn($manager, 'id');

            $data[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager,
            ];
        }

        // 清除没有子合伙人的
        // 这里相当于, 没有manager的人要去除
        // 主要给下面去重使用
        $x = ArrayHelper::getColumn($data, 'manager');
        foreach ($x as $k => $v) {
            if (!$v) {
                unset($x[$k]);
            }
        }

        // 去子合伙人
        // 存在于别人的团队中, 就是子合伙人
        // id 存在于 别的 manager中, 肯定是子合伙人
        foreach ($users as $key => $user) {
            foreach ($x as $item) {
                if (in_array($user, $item)) {
                    unset($users[$key]);
                }
            }
        }

        // 此时已经找出最顶层的合伙人了
        // var_dump($users);exit;

        // var_dump($data);exit;
        // 此数据后面还要用, 保存到类中
        self::$users = $data;

        $needs = self::getData($users);
        $list = self::getOrder($needs);

        // var_dump($list);exit;
        foreach ($list as &$item) {
            if ($item['amount'] == 0) {
                continue;
            }

            // 极差, 减去第1层全部子团队佣金
            $first_child = self::firstChild($item, $list);

            $item['first_child'] = $first_child;
            $item['real_amount'] = $item['amount'] - $first_child;

            // 减去已返的
            $done = (float) MonthProfit::find()
                ->where(['user_id' => $item['id']])
                ->andWhere(['type' => self::$type])
                ->sum('real_commission');

            // var_dump($item['real_amount'], $done);

            $item['done'] = $done;
            $item['real_amount'] = $item['real_amount'] - $done;
        }

        return $list;
    }

    private static function firstChild($child, $users)
    {

        $sum = 0;

        foreach ($child['manager'] as $id) {

            // 关系链上, 第1个运营中心
            // $first = Chain::getFirstOperator($id);
            $first = Chain::getReferrerChainOneId($id, [
                UserLevel::$keys['vip4'],
                UserLevel::$keys['vip5']
            ]);

            // 如果第1个推荐人, 刚好是$child,
            // 则说明 此子合伙人是 $child的第1层 子团队
            if ($first && $first['id'] == $child['id']) {
                if (isset($users[$id]) && isset($users[$id]['amount'])) {
                    $sum += $users[$id]['amount'];
                }
            }
        }

        return $sum;
    }

    // 为了少查数据库, 获取相应数据
    private static function getData($users)
    {
        $needs = [];
        foreach ($users as $user) {
            foreach (self::$users as $item) {
                if ($user == $item['id']) {
                    $needs[] = $item;
                    break;
                }
            }
        }
        return $needs;
    }

    private static function getOrder($users, $list = [])
    {
        foreach ($users as $user) {
            if (!key_exists($user['id'], $list)) {
                // 订单总金额
                $total = self::_order(array_merge([$user['id']], $user['children']));
                $list[$user['id']] = $user;
                $list[$user['id']]['total'] = $total;
                // 佣金与比例
                $x = self::_amount($total);
                $list[$user['id']]['amount'] = $x[0];
                // 这里改成单价了
                $list[$user['id']]['ratio'] = $x[1];
            }

            // 操作子团队业绩
            if (!empty($user['manager'])) {
                $manager = self::getData($user['manager']);
                $list = self::getOrder($manager, $list);
            }
        }

        return $list;
    }

    // 订单
    private static function _order($ids)
    {
        $price = self::$type == 1 ? SetUserUp::getLastOne()->vip1 : SetUserUp::getLastOne()->vip2;


        $orders = Order::find()
            // ->where(['is_repeat' => 1])
            ->andWhere(['user_id' => $ids])
            // 上个月的
            // 这里用累计了
            // ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
            // 云仓提货不算
            ->andWhere(['is_extract' => 0])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            // ->select(['id', 'total_pay', 'total_freight'])
            // ->asArray()
            // ->all();

            // 这里改成单量了
            // ->andWhere(['total_price' => SetUserUp::getLastOne()->vip1])
            ->andWhere(['total_price' => $price])
            ->count();

        return (int) $orders;

        $sum = 0;
        foreach ($orders as $order) {
            $sum += $order['total_pay'] - $order['total_freight'];
        }

        return $sum;
    }

    // 佣金
    private static function _amount($total)
    {
        // $set = SetUserUp::getLastOne();
        //
        // $ratio = 0;
        // if ($total >= $set->new_repeat_start3) {
        //     $ratio = $set->new_repeat_ratio3;
        // } else if ($total >= $set->new_repeat_start2) {
        //     $ratio = $set->new_repeat_ratio2;
        // } else if ($total >= $set->new_repeat_start1) {
        //     $ratio = $set->new_repeat_ratio1;
        // }
        //
        // return [$ratio * $total / 100, $ratio];

        // $total = (int)$total;

        // var_dump($total);

        $model = self::$type == 1 ? ZSetting::find()
            ->where(['<=', 'start', $total])
            ->andWhere(['>=', 'end', $total])
            ->one()
            :
            ZSetting2::find()
                ->where(['<=', 'start', $total])
                ->andWhere(['>=', 'end', $total])
                ->one();

        if ($model) {
            // $ratio = $model->amount / 100;
            $price = $model->amount;
            return [$total * $price, $price];
        }

        return [0, 0];
    }

    // 补贴 旅游 差旅 会议
    public static function getAmount($box)
    {
        // 这里取整
        $box = (int)$box;

        $model = ZSetting::find()
            ->where(['<=', 'start', $box])
            ->andWhere(['>=', 'end', $box])
            ->one();
        if ($model) {
            return [$model->amount * $box, $model->amount2 * $box, $model->amount3 * $box, $model->amount4 * $box];
        }

        return [0, 0, 0, 0];
    }

    // 需要减去的, 第一级团队的金额
    public static function getFirstAmount($r_id)
    {
        // 最后面放盒数, 前面为金额
        $sum = [0, 0, 0, 0, 0];

        $list = User::find()
            ->where(['referrer_id' => $r_id])
            ->select(['id'])
            ->column();

        foreach ($list as $id) {

            $children = Chain::getChildrenAll($id);
            $children = ArrayHelper::getColumn($children, 'id');
            $children = array_merge([$id], $children);

            $box = (float) Order::find()
                ->where(['user_id' => $children])
                // 本月
                ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
                ->sum('box');
            $amount = self::getAmount($box);

            $sum[0] += $amount[0];
            $sum[1] += $amount[1];
            $sum[2] += $amount[2];
            $sum[3] += $amount[3];
            $sum[4] += $box;
        }

        return $sum;
    }
}